package h0907;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 两个队列实现一个栈
 * @date 2024/9/7 15:13
 */
public class MyStack {
    Queue<Integer> queue1 = new LinkedList<>();
    Queue<Integer> queue2 = new LinkedList<>();

    public void push(int x) {
        queue1.offer(x);
    }

    public int pop() {
        if (!queue1.isEmpty()) {
            while (queue1.size()>1){
                queue2.offer(queue1.remove());
            }
            int popEle = queue1.remove();
            queue1=queue2;
            queue2=new LinkedList<>();
            return popEle;
        } else {
            throw new RuntimeException("栈为空");
        }
    }

    public int top() {
        if (!queue1.isEmpty()) {
            while (queue1.size()>1){
                queue2.offer(queue1.remove());
            }
            int top = queue1.peek();
            queue2.offer(queue1.remove());
            queue1=queue2;
            queue2=new LinkedList<>();
            return top;
        } else {
            throw new RuntimeException("栈为空");
        }
    }

    public static void main(String[] args) {
        MyStack stack=new MyStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        stack.push(45);
        System.out.println(stack.top());
        stack.pop();
        stack.pop();
        stack.pop();
        System.out.println(stack.pop());
    }
}
